<template>
  <div id="multi-store-select">
    <van-tree-select
        height="60vw"
        :items="storeTreeList"
        :main-active-index.sync="activeIndex"
        :active-id.sync="activeId"
        @click-item="changeItem"
    />
  </div>
</template>

<script>
export default {
  name: "MultiStoreSelect",
  props: {
    value: {
      type: Array,
      default: () => {
        return [];
      }
    }
  },
  data() {
    return {
      activeIndex: 0,
      activeId: [],
    }
  },
  watch: {
    value: {
      handler(val) {
        this.activeId = val;
        const { storeTreeList } = this.$store.state.options;
        const indexSet = new Set()
        storeTreeList.forEach((item, index) => {
          item.children.forEach(store => {
            if (this.activeId.includes(store.id)) indexSet.add(index);
          })
        })

        const sortedArr = [...indexSet].sort((a, b) => a - b);
        if (sortedArr.length > 0) this.activeIndex = sortedArr[0];
      },
      immediate: true
    }
  },
  methods: {
    changeItem() {
      this.$emit('update:value', this.activeId);
    }
  },
  computed: {
    storeTreeList() {
      const { storeTreeList } = this.$store.state.options;
      storeTreeList.forEach(item => {
        const count = item.children?.filter(store => this.activeId.includes(store.id)).length ?? 0;
        item.badge = count || null;
      });

      return storeTreeList;
    }
  }
}
</script>

<style lang="scss">

</style>
